/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package global.sandbox.xmlutilities.demo;

import global.sandbox.xmlutilities.XMLTools;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.transform.Source;
import org.w3c.dom.Document;

public class XMLLoading {
    
    public static Document loadXMLFromResourceAsDocument(Class clazz, String name)
            throws NoSuchResourceException, XMLLoadingException {
        InputStream is = clazz.getResourceAsStream(name);
        
        if (is == null) {
            throw new NoSuchResourceException(name);
        }
        
        try {
            return XMLTools.loadDocumentFromStream(is);
        } catch (Exception ex) {
            throw new XMLLoadingException(ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                throw new XMLLoadingException(ex);
            }
        }
    }
    
    public static Source loadXMLFromResourceAsSource(Class clazz, String name)
            throws NoSuchResourceException, XMLLoadingException {
        return XMLTools.documentToDOMSource(
                loadXMLFromResourceAsDocument(clazz, name));
    }
    
    public static class NoSuchResourceException extends Exception {
        
        private static final long serialVersionUID = 1L;
        
        public NoSuchResourceException(String resourceName) {
            super(resourceName);
        }
        
    }
    
    public static class XMLLoadingException extends Exception {
        
        private static final long serialVersionUID = 1L;
        
        public XMLLoadingException(Throwable cause) {
            super(cause);
        }
        
    }
    
}
